import { BrowserWindow, ipcMain } from 'electron'
import { spawn } from 'node:child_process'
import path from 'node:path'
import http from 'node:http'
import { IPC_CHANNELS } from 'shared/ipcChannels'
import { createLogger } from '#/logger'
import { getTTSService } from '#/services/TTSService'
import { typedIpcMainHandle } from '#/utils'
import { PRESET_VOICES } from 'shared/constants'

const logger = createLogger('AI助播')

/**
 * 检查 Edge-TTS 本地服务是否运行
 */
async function checkEdgeTTSService(apiUrl: string): Promise<boolean> {
  return new Promise((resolve) => {
    try {
      const url = new URL(apiUrl)
      const options = {
        hostname: url.hostname,
        port: url.port || 5000,
        path: '/',
        method: 'GET',
        timeout: 2000,
      }

      const req = http.request(options, (res) => {
        resolve(res.statusCode === 200 || res.statusCode === 404)
      })

      req.on('error', () => {
        resolve(false)
      })

      req.on('timeout', () => {
        req.destroy()
        resolve(false)
      })

      req.end()
    } catch (error) {
      resolve(false)
    }
  })
}

/**
 * 启动 Edge-TTS 本地服务
 */
async function startEdgeTTSService(): Promise<void> {
  return new Promise((resolve, reject) => {
    try {
      // 获取脚本路径
      const isDev = process.env.NODE_ENV === 'development'
      const scriptPath = isDev
        ? path.join(process.cwd(), 'scripts', 'start_edge_tts.bat')
        : path.join(process.resourcesPath, 'scripts', 'start_edge_tts.bat')

      logger.info('启动 Edge-TTS 服务:', scriptPath)

      // 使用 cmd 启动批处理脚本（新窗口）
      const child = spawn('cmd.exe', ['/c', 'start', 'cmd.exe', '/k', scriptPath], {
        detached: true,
        stdio: 'ignore',
      })

      child.unref()

      // 等待服务启动
      setTimeout(() => {
        logger.info('Edge-TTS 服务已启动')
        resolve()
      }, 3000)
    } catch (error) {
      logger.error('启动 Edge-TTS 服务失败:', error)
      reject(error)
    }
  })
}

function setupIpcHandlers() {
  // 监听停止音频请求，并转发给所有渲染进程
  ipcMain.on('tts:stop-audio', () => {
    logger.info('收到停止音频请求')
    const allWindows = BrowserWindow.getAllWindows()
    for (const win of allWindows) {
      win.webContents.send('tts:stop-audio')
    }
  })

  // 合成语音
  typedIpcMainHandle(
    IPC_CHANNELS.tasks.aiAssist.synthesizeVoice,
    async (_, params: { text: string; voiceConfig: AIAssistConfig }) => {
      try {
        logger.info(`收到评论播报请求: ${params.text}`)

        // 如果是 Edge-TTS，先检查服务是否运行
        if (params.voiceConfig.provider === 'edge') {
          const apiUrl = params.voiceConfig.edge?.apiUrl || 'http://localhost:5000'
          const isRunning = await checkEdgeTTSService(apiUrl)
          
          if (!isRunning) {
            logger.info('Edge-TTS 服务未运行，正在启动...')
            try {
              await startEdgeTTSService()
              // 再次检查服务是否启动成功
              const recheckRunning = await checkEdgeTTSService(apiUrl)
              if (!recheckRunning) {
                return {
                  success: false,
                  error: 'Edge-TTS 服务未运行，请先启动服务',
                }
              }
            } catch (error) {
              logger.error('启动 Edge-TTS 服务失败:', error)
              return {
                success: false,
                error: 'Edge-TTS 服务未运行，请先启动服务',
              }
            }
          }
        }

        const ttsService = getTTSService()
        const result = await ttsService.synthesizeAndPlay(params)
        return result
      } catch (error) {
        logger.error(`语音合成失败: ${error instanceof Error ? error.message : String(error)}`)
        return {
          success: false,
          error: error instanceof Error ? error.message : String(error),
        }
      }
    },
  )

  // 测试配置
  typedIpcMainHandle(
    IPC_CHANNELS.tasks.aiAssist.testVoiceConfig,
    async (_, config: AIAssistConfig) => {
      try {
        logger.info(`收到TTS配置测试请求 - 厂商: ${config.provider || '未设置(默认aliyun)'}`)
        logger.info('配置详情:', {
          provider: config.provider,
          hasAliyunConfig: !!config.aliyun?.accessKeyId,
          hasTencentConfig: !!config.tencent?.secretId,
          hasEdgeConfig: !!config.edge?.voice,
        })

        // 如果是 Edge-TTS，先检查服务是否运行
        if (config.provider === 'edge') {
          const apiUrl = config.edge?.apiUrl || 'http://localhost:5000'
          logger.info('检查 Edge-TTS 服务状态...')
          
          const isRunning = await checkEdgeTTSService(apiUrl)
          
          if (!isRunning) {
            logger.info('Edge-TTS 服务未运行，正在启动...')
            try {
              await startEdgeTTSService()
              // 再次检查服务是否启动成功
              const recheckRunning = await checkEdgeTTSService(apiUrl)
              if (!recheckRunning) {
                return {
                  success: false,
                  error: 'Edge-TTS 服务启动失败，请手动运行 scripts/start_edge_tts.bat',
                }
              }
              logger.success('Edge-TTS 服务启动成功')
            } catch (error) {
              logger.error('启动 Edge-TTS 服务失败:', error)
              return {
                success: false,
                error: '无法启动 Edge-TTS 服务，请手动运行 scripts/start_edge_tts.bat',
              }
            }
          } else {
            logger.info('Edge-TTS 服务已运行')
          }
        }

        const ttsService = getTTSService()
        const result = await ttsService.testConfig(config)
        return result
      } catch (error) {
        logger.error(`TTS配置测试失败: ${error instanceof Error ? error.message : String(error)}`)
        return {
          success: false,
          error: error instanceof Error ? error.message : String(error),
        }
      }
    },
  )

  // 获取预设音色列表
  typedIpcMainHandle(IPC_CHANNELS.tasks.aiAssist.getPresetVoices, async () => {
    return PRESET_VOICES
  })

  // 克隆音色 (暂时返回未实现)
  typedIpcMainHandle(
    IPC_CHANNELS.tasks.aiAssist.cloneVoice,
    async (
      _,
      _params: {
        audioFile: string
        voiceName: string
        config: Pick<AIAssistConfig, 'aliyun'>
      },
    ) => {
      logger.warn('声音克隆功能暂未实现')
      // TODO: 实现声音克隆功能
      // 这需要调用阿里云的声音克隆 API
      return {
        success: false,
        error: '声音克隆功能暂未实现，请在阿里云控制台手动克隆',
      }
    },
  )
}

export default setupIpcHandlers


